
package hk.ces.oxfam.patch.transaction;

import hk.ces.oxfam.patch.TransactionPatch;
import hk.ces.oxfam.patch.db.result.SQLResult;
import hk.ces.oxfam.patch.db.sql.PreparedSQL;
import hk.ces.oxfam.patch.sql.QueryUtil;
import hk.ces.oxfam.patch.xml.SQLResultXML;
import hk.ces.oxfam.patch.xml.factory.SQLResultXMLFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author ReutyCheng
 */
public class DuplicateBatchNoPatch implements TransactionPatch
{
  private final String getDuplicationBatchNoSql = "select temp.batchno from (select batchno, count(id) as count from batch where disabled = ? and event_id is not null group by batchno) as temp where temp.count > 1";

  public void run(Connection connection) throws SQLException
  {
    this.findDuplicationBatchNo(connection);
  }

  private List<String> getDuplicationBatchNo(Connection connection) throws SQLException
  {
    String sql = getDuplicationBatchNoSql;
    Object[] params = new Object[]{false};
    List<String> list = QueryUtil.column(connection, new hk.ces.oxfam.patch.sql.PreparedSQL(sql, params), 0, String.class);

    return list;
  }

  private void findDuplicationBatchNo(Connection connection) throws SQLException
  {
    String sql = getDuplicationBatchNoSql;
    Object[] params = new Object[]{false};
    SQLResult result = hk.ces.oxfam.patch.db.SQLUtil.query(connection, new PreparedSQL(sql, params));

    SQLResultXMLFactory factory = new SQLResultXMLFactory("DuplicationBatchNo");
    factory.setXMLItems(new SQLResultXML(result));
    factory.writeToFile();
  }
}
